package com.usian.wemedia.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Component
public class KODOUtils {

    @Value("${kodo.baseurl}")
    private String kodoBaseUrl;

    // 七牛云的 ACCESSKEY
    private final String ACCESSKEY = "d8YW8vLb3H7uI1XWrVKQ_yhnkn9ppE96P5i4VU7B";
    // 七牛云的 SECRETKEY 是ACCESSKEY密码
    private final String SECRETKEY = "eo9g8eae3KCBmqwbuW0YW6vYh7ZJKj9r0e6lAMw5";
    // 命名空间
    private final String BUCKET = "hell01";


    public String saveImages(MultipartFile file) {
        // 获取file
        String fileName = file.getOriginalFilename();
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region1());
        UploadManager uploadManager = new UploadManager(cfg);
        // 获取文件后缀名
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
        Auth auth = Auth.create(ACCESSKEY, SECRETKEY);
        String upToken = auth.uploadToken(BUCKET);
        try {
            Response response = uploadManager.put(file.getBytes(), fileName, upToken);
            if(response.isOK() && response.isJson()){
                //获取地址
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                // 获取的文件名
                System.out.println(putRet.key);
                return kodoBaseUrl+putRet.key;
            }
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 封装删除方法

}
